﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using db = DataContext;

namespace WebApplication
{
	public partial class Admin : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if (Request.QueryString["do"] == "out")
			{
				Session.Abandon();
				Response.Redirect("admin.aspx", true);
			}

			if (Session["User"] != null)
			{
				Server.Transfer("~/admin/frame.aspx");
				Response.End();
			}

			if (!string.IsNullOrEmpty(Request.Form["safecode"]))
			{ //检测登录
				db.Account account = null;

				if (Request.Form["safecode"].ToLower().Equals(Session["ValidateCode"].ToString().ToLower())
					&& Login(Request.Form["loginname"], MD5.Create(Request.Form["passport"]), out account))
				{
					Session.Remove("ValidateCode");
					Session["User"] = account;
				}
				Response.Redirect("admin.aspx", true);
			} else
			{
				Server.Execute("~/admin/login.aspx");
			}
		}

		private bool Login(string name, string pass, out db.Account account)
		{
			using (db.DbDataContext context = new db.DbDataContext())
			{
				if (context.Account.Count(x => x.AccountName.Equals(name) && x.Passport.Equals(pass)) == 1)
				{
					account = context.Account.Single(x => x.AccountName.Equals(name) && x.Passport.Equals(pass));
					return true;
				}
			}
			account = null;
			return false;
		}
	}
}